package lt.mockos.app.client.cpu.hw;

import lt.mockos.app.client.cpu.hw.descriptor.ProcessDescriptor;
import lt.mockos.app.client.cpu.hw.descriptor.ResourceDescriptor;
import lt.mockos.app.client.cpu.hw.type.ProcessPriority;
import lt.mockos.app.client.cpu.hw.type.ProcessStatus;
import lt.mockos.app.client.cpu.hw.type.ProcessType;

public class ProcessesManager {

    private SuperMemory superMemory;
    private ResourcesManager resourcesManager;

    public ProcessDescriptor createProcess(String title, ProcessDescriptor parent, ProcessPriority priority, ProcessType type) {
        ProcessDescriptor pd = new ProcessDescriptor(title, priority, parent, type);
        superMemory.add(pd);

        return pd;
    }

    public ProcessesManager(SuperMemory superMemory, ResourcesManager resourcesManager) {
        this.resourcesManager = resourcesManager;
        this.superMemory = superMemory;
    }

    public void removeProcess(ProcessDescriptor pd) {
        for (ResourceDescriptor rd : superMemory.getResourceDescriptors()) {
            if (rd.getParent() == pd)
                resourcesManager.freeResource(rd);
            resourcesManager.removeResource(rd, pd);
        }

        for (ProcessDescriptor d : superMemory.getProcessDescriptors()) {
            if (d.getParent() == pd)
                removeProcess(d);
        }
        superMemory.remove(pd);
    }

    public void stopProcess(ProcessDescriptor pd) {
        pd.setStatus(ProcessStatus.STOP);
    }

    public void startProcess(ProcessDescriptor pd) {
        for (ResourceDescriptor rd : superMemory.getResourceDescriptors()) {
            if (rd.getUsingProcess() == pd)
                pd.setStatus(ProcessStatus.READY);
        }

        if (pd.getStatus() == ProcessStatus.STOP)
            pd.setStatus(ProcessStatus.BLOCK);
    }

    public boolean changeProcess() {
        return true;
    }
}
